package dals

import (
	"fmt"
	"gitee.com/chejiangyi/bsfgo/core/db"
	"gitee.com/chejiangyi/bsfgo/core/utils"
	"gitee.com/chejiangyi/bsfgo/demo/domain/auto_models"
	"strings"
)

var DbUserDal *UserDal = &UserDal{}

type UserDal struct {
}

func (u UserDal) Insert(conn *db.DbConn, user *auto_models.User) {
	sql := "INSERT INTO tb_user (name, create_time) VALUES (?, ?)"
	r := conn.Exec(sql, user.Name, user.CreateTime)
	user.Id = int(conn.GetLastInsertID(r))
}

func (u UserDal) Update(conn *db.DbConn, user *auto_models.User) {
	sql := "UPDATE tb_user SET name = ?, psd =?, create_time = ? WHERE id = ?"
	conn.Exec(sql, user.Name, user.Psd, user.CreateTime, user.Id)
}

func (u UserDal) Select(conn *db.DbConn, id int) *auto_models.User {
	sql := "select * from tb_user WHERE id = ?"
	var user []auto_models.User
	conn.Rows(&user, sql, id)
	return &user[0]
}

func (u UserDal) Login(conn *db.DbConn, username string, password string) *auto_models.User {
	sql := "select * from tb_user WHERE name = ? and psd = ?"
	var user []auto_models.User
	conn.Rows(&user, sql, username, password)
	if len(user) > 0 {
		return &user[0]
	}
	return nil
}

func (u UserDal) Search(conn *db.DbConn, name string, createTimeFrom string, createTimeTo string, pageIndex int, pageSize int, count *int64) []auto_models.User {
	var condition strings.Builder
	var ps []interface{}
	condition.WriteString("from tb_user where 1=1")
	//vs := []any{1, 2, 3, 4, 5}
	//conn.AppendSqlCondition(&condition, &ps, true, " and id in ("+strings.Repeat("?", len(vs))+")", v2...)
	//name
	conn.AppendSqlCondition(&condition, &ps, !utils.StringUtil.IsEmpty(name), " and name like concat('%', ?, '%')", name)
	//create_time
	conn.AppendSqlCondition(&condition, &ps, !utils.StringUtil.IsEmpty(createTimeFrom), " and create_time >?", createTimeFrom)
	conn.AppendSqlCondition(&condition, &ps, !utils.StringUtil.IsEmpty(createTimeTo), " and create_time <?", createTimeTo)

	sql := "select * " + condition.String() + " order by id desc " + fmt.Sprintf(" limit %v,%v", (pageIndex-1)*pageSize, pageSize)
	countSql := "select count(0) " + condition.String()
	var user []auto_models.User
	conn.Rows(&user, sql, ps...)
	conn.Scalar(count, countSql, ps...)
	return user
}

func (u UserDal) GetById(conn *db.DbConn, id int) *auto_models.User {
	sql := "select * from tb_user WHERE id = ?"
	var user []auto_models.User
	conn.Rows(&user, sql, id)
	if len(user) > 0 {
		return &user[0]
	}
	return nil
}
